// pages/common/pages/buynow/buynow.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //地址信息
    userName: '',
    address: '点击选择配送地址',
    tel: '',

    //总金额
    total: 0,

    //商品信息
    goods:null, 
    //商品数量
    num:0,
    url:''      
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let good = JSON.parse(options.goods);
    let num = options.num;
    let price = good.price;
    let total = price * num;
    // let imgBase = good.imgBase64.replace(/[\r\n]/g, "");
    let url = good.url;
    //接受传递过来的购买的商品
    this.setData({
      goods:good,
      num: num,
      total: total,
      url: url
    });

  },
   /**
   * 选择地址
   */
  chooseAddress() {
    let _this = this;
    wx.chooseAddress({
      success(res) {    //获取地址成功
        _this.setData({
          //用户名
          userName: res.userName,
          //地址
          address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
          //电话
          tel: res.telNumber
        })
      }
    })
  },
  /**
   * 提交订单
   */
  submitOrder() {
    this.buy();
  },
  //后台接口立即购买生成订单
  buy() {
    let _this = this;
    let goodsId = _this.data.goods.id;
    let addRess = _this.data.userName + " " + _this.data.address + " " + _this.data.tel;   //拼接地址：用户名 地址 电话
    console.log(addRess)
    var header = app.globalData.header;

   //获取app.js中的请求头
    if (this.data.userName == '' || this.data.address == '' || this.data.tel == ''){
      wx.showToast({
        title: '请完善配送信息',
        icon: "none"
      })
      return;
    }else{
      wx.request({
        url: app.globalData.ipPort +'/front/order/create/single',
        method: 'post',
        header: {
          'Cookie': app.globalData.header.Cookie,
          'Content-Type': 'application/x-www-form-urlencoded' 
        },
        data: {
          goodsId: goodsId ,
          buyCount: _this.data.num,
          address: addRess,
          userId: app.globalData.userId
        },
        success(res) {
          if (res.data.code == 200) {
            wx.showToast({
              title: "下单成功，等待审核！",
              icon: "none"
            })
            _this.setData({
              goods: null,
            })
            wx.redirectTo({
              url: "/pages/common/pages/index/index"
            })
          } else {
            _this.setData({
              goods: null,
            })
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          }
        }, fail(res) {
          _this.setData({
            goods: null,
          })
          wx.showToast({
            title: res.msg,
            icon: "none"
          })
        }
      })
    }
    
  },
})